/****************************************************
	文件：ContextBase.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/2/7 22:6:7
	功能：Unit 上下文
*****************************************************/

using System;
using UnityEngine;

namespace HTFW.Core
{
    public class UnitContext : IContext
    {
        MonoBehaviour mMono;

        public ContextType ContextType { get; set; }
        public ContextScope ContextScope { get; set; }
        public Action<IContext> OnInit { get; set; }
        public Action<IContext> OnDispose { get; set; }


        public ResContext ResContext;
        public TimerContext TimerContext;
        public CoroutineContext CoroutineContext;
        public EventContext EventContext;


        public void Init(params object[] args)
        {
            mMono = (MonoBehaviour) args[0];

            ResContext = ContextManager.Instance.CreateContext<ResContext>(ContextType.Res, ContextScope);

            TimerContext = ContextManager.Instance.CreateContext<TimerContext>(ContextType.Timer, ContextScope);

            CoroutineContext =
                ContextManager.Instance.CreateContext<CoroutineContext>(ContextType.Coroutine, ContextScope);

            EventContext = ContextManager.Instance.CreateContext<EventContext>(ContextType.Event, ContextScope);

            ResContext.Init();
            TimerContext.Init();
            CoroutineContext.Init(mMono);
            EventContext.Init();
        }

        public void Dispose()
        {
            if (ResContext != null)
            {
                ContextManager.Instance.DeleteContext(ResContext);
                ResContext = null;
            }

            if (TimerContext != null)
            {
                ContextManager.Instance.DeleteContext(TimerContext);
                TimerContext = null;
            }

            if (CoroutineContext != null)
            {
                ContextManager.Instance.DeleteContext(CoroutineContext);
                CoroutineContext = null;
            }

            if (EventContext != null)
            {
                ContextManager.Instance.DeleteContext(EventContext);
                EventContext = null;
            }

            OnInit = null;
            OnDispose = null;
        }
    }
}